package com.example.gesturerecognition.service;

import com.example.gesturerecognition.mapper.UserMapper;
import com.example.gesturerecognition.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import static com.sun.tools.doclint.Entity.or;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public static final String emailNull = "邮箱为空值";
    public static final String emailRepeat = "邮箱重复";
    public static final String passwordCheckError = "密码检验错误";
    public static final String passwordError = "密码输入错误";
    public static final String registerSuccess = "注册成功";
    public static final String registerFailure = "注册失败";
    public static final String loginSuccess = "登录成功";

    //用户注册
    public String register(@RequestBody User user)
    {
        //检查user对象中的数据是否符合要求
        if(user.getEmail() == null)//如果email没有内容
        {
            return emailNull;
        }
        else if(userMapper.selectEmail(user.getEmail()) > 0)//如果email已经有注册
        {
            return emailRepeat;
        }
        else if(!passwordCheck(user.getPassword()))//如果密码检验错误
        {
            return passwordCheckError;
        }
        else  //检验正确，进行注册
        {
            int result = userMapper.insertUser(user);
            if(result == 1)
                return registerSuccess;
            else
                return registerFailure;
        }
    }

    //密码检验方法
    public boolean passwordCheck(String password)
    {
        if(password.length() < 8 || password.length() > 16)  //密码位数不符合要求要求
        {
            return false;
        }

        /*密码必须含有数字和字母*/
        boolean digital = false;
        boolean letter = false;
        for (int i = 0; i < password.length();i++)
        {
            if(Character.isDigit(password.charAt(i)))
                digital = true;
            if(Character.isLetter(password.charAt(i)))
                letter = true;
            if(digital && letter)//表示含有数字和字母,返回true
                return true;
        }
        return false;
    }

    public String login(String email, String password)
    {
        //对邮箱和密码进行检验
        if(userMapper.selectEmail(email) == 0)//表示用户不存在
            return emailNull;
        else if(userMapper.selectPassword(email,password) == 0)//表示密码不正确
            return passwordError;
        else
            return loginSuccess;
    }
}
